<?php

/**
 * Description of Connection
 * @package Core
 * @author superx
 */
class Core_Db_Connection {

    protected static $_stack = array();
    protected static $_timeout = 1;

//    public static function setPersist($persist = true){
//        self::$_persist = $persist;
//    }

    private function __construct() {

    }

    /**
     * @param string $name
     * @return PDO
     */
    public static function getInstance($name = 'default') {
        $conf = Core_Config::get('db.' . $name);
        $dsn = "mysql:host={$conf['host']};port={$conf['port']};charset={$conf['charset']};dbname={$conf['dbname']}";
        $key = md5($dsn . ";username={$conf['username']};passwd={$conf['passwd']}");
        if (empty(self::$_stack[$key])) {
            $dbh = new PDO($dsn, $conf['username'], $conf['passwd'], array(
//                PDO::ATTR_PERSISTENT => $conf['persist'],
                PDO::ATTR_TIMEOUT => self::$_timeout,
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
            ));
            self::$_stack[$key] = $dbh;
        }
        return self::$_stack[$key];
    }

    public static function closeAll() {
        self::$_stack = array();
        gc_collect_cycles();
    }

}
